package com.example.cheng.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.db.sql.Order;
import com.example.cheng.mapper.UserMapper;
import com.example.cheng.poji.*;
import com.example.cheng.utils.BigDecimalManager;
import com.example.cheng.utils.OrderNoCreate;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController

public class Controller {
    @Autowired
    private UserMapper usermapper;


    public String getCurrentTime(){
        Date currentDate = new Date();
        // 定义日期格式化的模式
        String pattern = "yyyy-MM-dd HH:mm:ss";
        // 创建SimpleDateFormat对象并设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        // 调用format()方法将日期对象转换为指定格式的字符串
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }

    @RequestMapping("/updateDeviceName")
    public BaseResult updateDeviceName(@RequestBody DeviceClassListDtoOut dtoIn) {
        usermapper.updateDeviceName(dtoIn);
        return BaseResult.sucess("修改成功");
    }
    @RequestMapping("/updateDeviceClassXiajia")
    public BaseResult updateDeviceClassXiajia(@RequestBody DeviceClassListDtoOut dtoIn) {
        dtoIn.setXiajia(true);
        usermapper.updateDeviceClassXiajia(dtoIn);
        return BaseResult.sucess("修改成功");
    }


    @RequestMapping("/deleteinventory")
    public BaseResult deleteinventoryItem(@RequestBody InventorysListDtoOut dtoIn) {
        usermapper.deleteinventoryItem(dtoIn);
        return BaseResult.sucess("删除成功");
    }
    @RequestMapping("/changeKuDataAction")
    public BaseResult changeKuDataAction(@RequestBody InventorysListDtoOut dtoIn) {
        usermapper.changeKuDataAction(dtoIn);
        return BaseResult.sucess("修改成功");
    }
    @RequestMapping("/chuku")
    public BaseResult chukuAction(@RequestBody InventorysListDtoOut dtoIn) {

        dtoIn.setUpdate_time(getCurrentTime());
        dtoIn.setStatus(2);
        usermapper.chukuAction(dtoIn);
        return BaseResult.sucess("出库成功");
    }
        @RequestMapping("/getInventorys")
    public BaseResult getInventorysAction(@RequestBody InventorysSearchDtoIn dtoIn) {
        Integer stat = (dtoIn.getPage() -1 ) * dtoIn.getSize();
        dtoIn.setPage(stat);
        System.out.print(dtoIn);
        List<InventorysListDtoOut> list = usermapper.getInventorysAction(dtoIn);
        List temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            InventorysListDtoOut item = list.get(i);
            item.setYname(usermapper.getDeviceName(item.getYid()));
            item.setFname(usermapper.getDeviceFName(item.getFid()));
            item.setUname(usermapper.getUserName(item.getUid()));
            temp.add(item);
        }
        return BaseResult.sucess(temp);
    }

    @RequestMapping("/inventorysAdd")
    public BaseResult inventorysAddAction(@RequestBody InventorysAddDtoIn dtoIn) {

        DeviceClassListDtoOut temp  = new DeviceClassListDtoOut();
        temp.setUse_type(true);
        temp.setId(dtoIn.getFid());
        usermapper.updateDeviceClass(temp);
        usermapper.inventorysAddAction(dtoIn);
        return BaseResult.sucess("添加成功");
    }
    @RequestMapping("/addDevice")
    public BaseResult addDevice(@RequestBody DeviceAddDtoIn dtoIn) {
        usermapper.addDeviceAction(dtoIn);
        return BaseResult.sucess("添加成功");
    }
    @RequestMapping("/addDeviceClass")
    public BaseResult addDeviceClass(@RequestBody DeviceClassAddDtoIn dtoIn) {
        usermapper.addDeviceClassAction(dtoIn);
        DeviceListDtoOut temp = new DeviceListDtoOut();
        temp.setId(dtoIn.getFid());
        temp.setUse_type(true);
        usermapper.updateDeviceUseType(temp);
        return BaseResult.sucess("添加成功");
    }

    @RequestMapping("/updateDeviceXiajia")
    public BaseResult updateDeviceXiajia(@RequestBody DeviceListDtoOut dtoIn) {
        dtoIn.setXiajia(true);
        usermapper.updateDeviceXiajia(dtoIn);
        return BaseResult.sucess("下架成功");
    }

    @RequestMapping("/getDeviceClass")
    public BaseResult getDeviceClass() {
        List<DeviceClassListDtoOut> list = usermapper.getDeviceClass();
        List temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            DeviceClassListDtoOut item = list.get(i);
            if(item.getXiajia() == false){
                item.setF_name(usermapper.getDeviceName(item.getFid()));
                temp.add(item);
            }
        }
        return BaseResult.sucess(temp);
    }
    @RequestMapping("/deleteDeviceClass")
    public BaseResult deleteDeviceClass(@RequestBody DeviceClassListDtoOut dtoIn) {
        usermapper.deleteDeviceClass(dtoIn);
        return BaseResult.sucess("删除成功");
    }

    @RequestMapping("/getDeviceClassById")
    public BaseResult getDeviceClassById(@RequestBody DeviceClassListDtoOut dtoIn) {
        List<DeviceClassListDtoOut> list = usermapper.getDeviceClassById(dtoIn);
        List temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            DeviceClassListDtoOut item = list.get(i);
            item.setF_name(usermapper.getDeviceName(item.getFid()));
        }
        System.out.print(list);
        return BaseResult.sucess(list);
    }


    @RequestMapping("/getDevices")
    public BaseResult getDevices() {
        List<DeviceListDtoOut> list = usermapper.getDevices();
        List temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            DeviceListDtoOut item = list.get(i);
            if(item.getXiajia() == false){
                temp.add(item);
            }
        }
        System.out.print(temp);
        return BaseResult.sucess(temp);
    }
    @RequestMapping("/getStoreList")
    public BaseResult getStoreList() {
        List<StoreListDtoOut> list = usermapper.getStoreList();
        System.out.print(list);
        return BaseResult.sucess(list);
    }

    @RequestMapping("/deleteDevice")
    public BaseResult deleteDevice(@RequestBody DeviceListDtoOut dtoIn) {
        usermapper.deleteDevice(dtoIn);
        return BaseResult.sucess("删除成功");
    }

    @RequestMapping("/updateDevice")
    public BaseResult updateDevice(@RequestBody DeviceListDtoOut dtoIn) {
        usermapper.updateDevice(dtoIn);
        return BaseResult.sucess("编辑成功");
    }

    @RequestMapping("/addStore")
    public BaseResult addStoreAtion(@RequestBody StoreListDtoIn dtoIn) {


        System.out.print(dtoIn);
        usermapper.addStoreAtion(dtoIn);
        return BaseResult.sucess("添加成功");
    }

    @RequestMapping("/updateStore")
    public BaseResult updateStore(@RequestBody StoreListDtoIn dtoIn) {
        dtoIn.setUpdate_time(new Date());
        System.out.print(dtoIn);
        usermapper.updateStore(dtoIn);
        return BaseResult.sucess("修改成功");
    }

    @RequestMapping("/deleteUser")
    public BaseResult deleteUser(@RequestBody UserAddDtoOut dtoIn) {
        usermapper.deleteUser(dtoIn);
        return BaseResult.sucess("删除成功");
    }

    @RequestMapping("/addUser")
    public BaseResult addUserAtion(@RequestBody UserAddDtoIn dtoIn) {

        UserAddDtoOut user = usermapper.getUser(dtoIn.getPhone());
        System.out.print(user);
        if(user == null){
            dtoIn.setPassword("111111");
            dtoIn.setRole("2");
            usermapper.addUserAtion(dtoIn);
            return BaseResult.sucess("添加成功");
        }else {
            return BaseResult.error("该用户已存在");

        }

    }
    @RequestMapping("/deleteStore")
    public BaseResult deleteStore(@RequestBody StoreListDtoIn dtoIn) {

        usermapper.deleteStore(dtoIn);
        return BaseResult.sucess("删除成功");
    }


    @RequestMapping("/getUserList")
    public BaseResult getUserList() {
        List<UserAddDtoOut> list = usermapper.getUserList();
        List<UserAddDtoOut> temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            UserAddDtoOut item = list.get(i);
            item.setStore(usermapper.getStoreName(item.getSid()));
            if(item.getRole().equals("2")){
                temp.add(item);
            }
        }
        System.out.print(temp);
        return BaseResult.sucess(temp);
    }

    @RequestMapping("/getGoodsList")
    public BaseResult getGoodsList(@RequestBody GoodsAddDtoIn dtoIn) {
        System.out.print(dtoIn);
        List<GoodsListDtoOut> list = usermapper.getGoodsList(dtoIn);
        List<GoodsListDtoOut> temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            GoodsListDtoOut item = list.get(i);
            if(item.getXiajia() == false){
                temp.add(item);
            }
        }
        return BaseResult.sucess(temp);
    }

    @RequestMapping("/addGoods")
    public BaseResult addGoodsAtion(@RequestBody GoodsAddDtoIn dtoIn) {
        usermapper.addGoodsAtion(dtoIn);
        System.out.print(dtoIn);
        return BaseResult.sucess("添加成功");
    }


    @RequestMapping("/updateGoods")
    public BaseResult updateGoods(@RequestBody GoodsListDtoOut dtoIn) {
        dtoIn.setUpdate_time(new Date());
        System.out.print(dtoIn);
        usermapper.updateGoods(dtoIn);
        return BaseResult.sucess("修改成功");
    }


    @RequestMapping("/xiajiaGoods")
    public BaseResult xiajiaGoods(@RequestBody GoodsListDtoOut dtoIn) {
        dtoIn.setUpdate_time(new Date());
        dtoIn.setXiajia(true);
        usermapper.xiajiaGoods(dtoIn);
        return BaseResult.sucess("商品已下架");
    }
    @RequestMapping("/deleteGoods")
    public BaseResult deleteGoods(@RequestBody GoodsListDtoOut dtoIn) {

        usermapper.deleteGoods(dtoIn);
        return BaseResult.sucess("删除成功");
    }


    @RequestMapping("/getDangweiList")
    public BaseResult getDangweiList(@RequestBody DangweiSearchDtoIn dtoIn) {

        List<DangweiDtoOut> list = usermapper.getDangweiList(dtoIn);
        return BaseResult.sucess(list);
    }

    @RequestMapping("/addDangwei")
    public BaseResult addDangweiAtion(@RequestBody DangweiAddDtoIn dtoIn) {
        usermapper.addDangweiAtion(dtoIn);
        System.out.print(dtoIn);

        return BaseResult.sucess("添加成功");
    }

    @RequestMapping("/updateDangwei")
    public BaseResult updateDangwei(@RequestBody DangweiDtoOut dtoIn) {
        dtoIn.setUpdate_time(new Date());
        usermapper.updateDangwei(dtoIn);
        return BaseResult.sucess("修改成功");
    }

    @RequestMapping("/deleteDangwei")
    public BaseResult deleteDangwei(@RequestBody DangweiDtoOut dtoIn) {

        usermapper.deleteDangwei(dtoIn);
        return BaseResult.sucess("删除成功");
    }

    @RequestMapping("/login")
    public BaseResult login(@RequestBody UserAddDtoIn dtoIn) {

        List<UserAddDtoOut> list = usermapper.login(dtoIn);
        for (int i = 0; i < list.size(); i++) {
            UserAddDtoOut item = list.get(i);
            item.setStore(usermapper.getStoreName(item.getSid()));
        }
        if (list.size() != 0) {
            return BaseResult.sucess(list.get(0));
        } else {
            return BaseResult.error("用户名或密码错误");
        }
    }


    @RequestMapping("/qinutoken")
    public BaseResult qinutoken() {
        String accessKey = "cXhwMiBRBiw_f2MPI6Pn-_IrpiQ5rQUQHQuu39be";
        String secretKey = "BiG0Yvlj3zWMqplekpV-ffqXncpF4x0C4hcxh0Be";
        String bucket = "cheng-images";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        System.out.println(upToken);
        Map map = new HashMap<>();
        map.put("toke", upToken);
        return BaseResult.sucess(map);
    }

    @RequestMapping("/addOrder")
    public BaseResult addOrderAtion(@RequestBody OrderAddDtoIn dtoIn) {
        String number = OrderNoCreate.randomOrderCode();
        dtoIn.setNumber(number);
        if (!dtoIn.getGoods().isEmpty()) {
            String[] goods = dtoIn.getGoods().split(",");
            for (int j = 0; j < goods.length; j++) {
                GoodsListDtoOut value = usermapper.getGoodInformation(goods[j]);
                if(value != null){
                    value.setUse_type(true);
                    value.setUpdate_time(new Date());
                    usermapper.updateGoods(value);
                }
            }
        }
        DangweiDtoOut dangwei = usermapper.getDangweiItem( String.valueOf(dtoIn.getDid()));
        dangwei.setUse_type(true);
        usermapper.updateDangwei(dangwei);
        usermapper.addOrderAtion(dtoIn);
        return BaseResult.sucess("添加成功");
    }

    @RequestMapping("/getOrdersList")
    public BaseResult getOrdersList(@RequestBody OrderSearchDtoIn dtoIn) {
        System.out.print(dtoIn);
        if(dtoIn.getUid() != "" && dtoIn.getUid() != null){
            UserAddDtoOut user = usermapper.getUserById(dtoIn.getUid());
            dtoIn.setDianzhang(user.getDianzhang());
            dtoIn.setSid(user.getSid());
        }else {
            dtoIn.setDianzhang(false);
        }
        Integer stat = (dtoIn.getPage() -1 ) * dtoIn.getSize();
        dtoIn.setPage(stat);
        List<OrderListDtoOut> list = usermapper.getOrdersList(dtoIn);
        List<OrderListDtoOut> temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            OrderListDtoOut item = list.get(i);
            List tempGoods = new ArrayList<>();
            if (!item.getGoods().isEmpty()) {
                String[] goods = item.getGoods().split(",");
                for (int j = 0; j < goods.length; j++) {
                    GoodsListDtoOut value = usermapper.getGoodInformation(goods[j]);
                   if(value != null){
                       value.setCprice(value.getPrice() - value.getNprice());
                       tempGoods.add(value);
                   }
                }
            }
            item.setGoodItems(tempGoods);
            DangweiDtoOut dangwei = usermapper.getDangweiItem(item.getDid());
            if(dangwei != null){
                item.setDangweiprice(dangwei.getPrice());
                item.setDangwei(dangwei.getName() + " / ¥" + dangwei.getPrice());
                item.setPercent(usermapper.getStorePercent(item.getSid()));
                item.setName(usermapper.getUserName(item.getUid()));
                item.setSame(usermapper.getStoreName(item.getSid()));
                temp.add(item);
            }
        }
        return BaseResult.sucess(temp);
    }

    @RequestMapping("/deleteOrder")
    public BaseResult deleteOrder(@RequestBody OrderListDtoOut dtoIn) {
        usermapper.deleteOrder(dtoIn);
        return BaseResult.sucess("删除成功");
    }

    @RequestMapping("/xiugaiOrder")
    public BaseResult xiugaiOrder(@RequestBody OrderListDtoOut dtoIn) {
        usermapper.xiugaiOrder(dtoIn);
        return BaseResult.sucess("修改成功");
    }
    @RequestMapping("/updateOrder")
    public BaseResult updateOrder(@RequestBody OrderListDtoOut dtoIn) {
        dtoIn.setUpdate_time(new Date());
        dtoIn.setStatus(2);
        usermapper.updateOrder(dtoIn);

        return BaseResult.sucess("修改成功");
    }

    /**
     * list 入参查询条件
     * service 业务层对象
     */
    @PostMapping("/createExcel")
    public BaseResult getExcelByPoi(@RequestBody CreateExcelDtoIn dtoIn) throws IOException {
        List<OrderListDtoOut> list = new ArrayList<>();
        if (!dtoIn.getValue().isEmpty()) {
            String[] orders = dtoIn.getValue().split(",");
            for (int j = 0; j < orders.length; j++) {
                OrderListDtoOut value = usermapper.getOrderById(orders[j]);
                list.add(value);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            OrderListDtoOut item = list.get(i);
            List tempGoods = new ArrayList<>();
            if (!item.getGoods().isEmpty()) {
                String[] goods = item.getGoods().split(",");
                for (int j = 0; j < goods.length; j++) {
                    GoodsListDtoOut value = usermapper.getGoodInformation(goods[j]);
                    if(value != null){
                        System.out.print(value);
                        value.setCprice(value.getPrice() - value.getNprice());
                        tempGoods.add(value);
                    }
                item.setGoodItems(tempGoods);
                }
            }
        }
        String url = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("发货单统计表");
        sheet.setDefaultColumnWidth(40);
        sheet.setDefaultRowHeightInPoints(20);
        List<String> hearList = new ArrayList<>();
//        hearList.add("姓名");
//        hearList.add("电话");
        hearList.add("地址");
        hearList.add("收货信息");
//        sheet.setColumnWidth(0,15*256);
//        sheet.setColumnWidth(1,15*256);
        sheet.setColumnWidth(0,80*256);
        sheet.setColumnWidth(1,80*256);

        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < hearList.size(); i++) {
            row.createCell(i).setCellValue(hearList.get(i));
        }
        for (int j = 0; j < list.size(); j++) {
            OrderListDtoOut dto = list.get(j);
            HSSFRow name_row = sheet.createRow(j + 1);
//            name_row.createCell(0).setCellValue(dto.getYname());
//
//            name_row.createCell(1).setCellValue(dto.getYphone());
            name_row.createCell(0).setCellValue(dto.getAddress());
            String good = "";
            if(dto.getGoodItems() != null){
                for (int k = 0; k < dto.getGoodItems().size(); k++) {
                    GoodsListDtoOut goodTemp = (GoodsListDtoOut) dto.getGoodItems().get(k);
                    if(k == 0){
                        good +=(k+1)+"."+ goodTemp.getName()+goodTemp.getType();
                    }else {
                        good += " " +(k+1)+"." + goodTemp.getName()+goodTemp.getType();
                    }
                }
            }
            name_row.createCell(1).setCellValue(good);
        }
        workbook.write(bos);
        byte[] barrays = bos.toByteArray();
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = "cXhwMiBRBiw_f2MPI6Pn-_IrpiQ5rQUQHQuu39be";
        String secretKey = "BiG0Yvlj3zWMqplekpV-ffqXncpF4x0C4hcxh0Be";
        String bucket = "cheng-images";
        String key = "excel/"+ "delivery/" + OrderNoCreate.getExcelName()+".xls";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(barrays, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);

                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        Map map = new HashMap<>();
        map.put("downurl", key);
        return BaseResult.sucess(map);
    }

    @PostMapping("/createOrderExcel")
    public BaseResult createOrderExcel(@RequestBody CreateExcelDtoIn dtoIn) throws IOException {

        List<OrderListDtoOut> list = new ArrayList<>();
        if (!dtoIn.getValue().isEmpty()) {
            String[] orders = dtoIn.getValue().split(",");
            for (int j = 0; j < orders.length; j++) {
                OrderListDtoOut value = usermapper.getOrderById(orders[j]);
                list.add(value);
            }
        }
        List<OrderListDtoOut> temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            OrderListDtoOut item = list.get(i);
            List tempGoods = new ArrayList<>();
            if (!item.getGoods().isEmpty()) {
                String[] goods = item.getGoods().split(",");
                for (int j = 0; j < goods.length; j++) {
                    GoodsListDtoOut value = usermapper.getGoodInformation(goods[j]);
                    if(value != null){
                        value.setCprice(value.getPrice() - value.getNprice());
                        tempGoods.add(value);
                    }
                }
            }
            item.setGoodItems(tempGoods);
            DangweiDtoOut dangwei = usermapper.getDangweiItem(item.getDid());
            item.setStore(usermapper.getStoreName(item.getSid()));
            if(dangwei != null){
                item.setDangweiprice(dangwei.getPrice());
                item.setDangwei(dangwei.getName());
                item.setPercent(usermapper.getStorePercent(item.getSid()));
                item.setName(usermapper.getUserName(item.getUid()));
                item.setSame(usermapper.getStoreName(item.getSid()));
                temp.add(item);
            }
        }


        String url = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("订单统计表");
        sheet.setDefaultColumnWidth(40);
        sheet.setDefaultRowHeightInPoints(20);
        List<String> hearList = new ArrayList<>();
        hearList.add("日期");
        hearList.add("营业厅名称");
        hearList.add("发展人");
        hearList.add("用户姓名");
        hearList.add("用户号码");
        hearList.add("档位");
        hearList.add("档位金额");
        hearList.add("补差款");
        hearList.add("现金");//0.05时候
        hearList.add("家电");
        hearList.add("成本");//家电拿货价
        hearList.add("利润");//档位金额-家电金额(现金,家电)
        hearList.add("利润溢出");
        hearList.add("利润溢出/2");
        hearList.add("利润5%");
        hearList.add("结算金额");
        hearList.add("结算金额/2");
        hearList.add("最终金额");//(结算金额/2)+利润溢出/2
        hearList.add("家电差价");
        hearList.add("发货状态");
        hearList.add("物流单号");

        for (int i = 0; i < hearList.size(); i++) {
            if(i == 0){
                sheet.setColumnWidth(i,20*256);

            }else if(i == 9){
                sheet.setColumnWidth(i,40*256);
            }else {
                sheet.setColumnWidth(i,15*256);
            }
        }

        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < hearList.size(); i++) {
            row.createCell(i).setCellValue(hearList.get(i));
        }
        for (int j = 0; j < list.size(); j++) {
            OrderListDtoOut dto = list.get(j);
            HSSFRow name_row = sheet.createRow(j + 1);
            double dangweijine = 0;
            if ( Double.parseDouble(dto.getPercent()) == 0.05) {
                dangweijine = BigDecimalManager.subtractionDouble(dto.getDangweiprice(),10);
            }else {
                dangweijine = dto.getDangweiprice();
            }
            dangweijine = BigDecimalManager.additionDouble(dangweijine,Double.parseDouble(dto.getBprice()));
            name_row.createCell(0).setCellValue(dto.getCreate_time());
            name_row.createCell(1).setCellValue(dto.getStore());
            name_row.createCell(2).setCellValue(dto.getName());
            name_row.createCell(3).setCellValue(dto.getYname());
            name_row.createCell(4).setCellValue(dto.getYphone());
            name_row.createCell(5).setCellValue(dto.getDangwei());
            name_row.createCell(6).setCellValue(dangweijine);
            double xprice = Double.parseDouble(dto.getXprice());//BigDecimalManager.additionDouble(Double.parseDouble(dto.getXprice()),Double.parseDouble(dto.getPercent()) == 0.05 ? 10 :0);
            name_row.createCell(7).setCellValue(dto.getBprice());
            name_row.createCell(8).setCellValue(xprice);

            String good = "";
            double chajichajia = 0;
            double jiadiantotal = 0;
            if(dto.getGoodItems() != null){
                for (int k = 0; k < dto.getGoodItems().size(); k++) {
                    GoodsListDtoOut goodTemp = (GoodsListDtoOut) dto.getGoodItems().get(k);
                    chajichajia = BigDecimalManager.additionDouble(chajichajia, goodTemp.getCprice());
                    jiadiantotal = BigDecimalManager.additionDouble(jiadiantotal, goodTemp.getPrice());

                    if(k == 0){
                        good +=(k+1)+"."+ goodTemp.getName()+goodTemp.getType();
                    }else {
                        good += " " +(k+1)+"." + goodTemp.getName()+goodTemp.getType();
                    }


                }
            }
            double total = BigDecimalManager.subtractionDouble(BigDecimalManager.subtractionDouble(dangweijine,Float.parseFloat(dto.getXprice())),jiadiantotal) ;
            double yichu = 0;

            double showToal = 0;
            if(total > 600){
                showToal = 600;
                yichu = BigDecimalManager.subtractionDouble(total, 600) ;
            }else {
                showToal = total;
            }
            double yichu2 = BigDecimalManager.divisionDouble(yichu,2,2);
            double shouxufei = BigDecimalManager.multiplicationDouble(total,Float.parseFloat(dto.getPercent()),2);
            if ( Double.parseDouble(dto.getPercent()) == 0.05) {
                if (shouxufei > 30) {
                    shouxufei = 30;
                }
            }
            double jiesuan = BigDecimalManager.subtractionDouble(showToal,shouxufei);
            double jiesuan2 = Double.parseDouble(dto.getPercent()) == 0.05 ? BigDecimalManager.divisionDouble(jiesuan,2,2) : 0;
            double jing = Double.parseDouble(dto.getPercent()) == 0.05 ? BigDecimalManager.additionDouble(yichu2,jiesuan2) : 0;
            double ben = BigDecimalManager.additionDouble(jiadiantotal,Double.parseDouble(dto.getXprice()));

            name_row.createCell(9).setCellValue(good);
            name_row.createCell(10).setCellValue(ben);

            name_row.createCell(11).setCellValue(showToal);
            name_row.createCell(12).setCellValue(yichu);
            name_row.createCell(13).setCellValue(yichu2);
            name_row.createCell(14).setCellValue(shouxufei);
            name_row.createCell(15).setCellValue(jiesuan);
            name_row.createCell(16).setCellValue(jiesuan2);
            name_row.createCell(17).setCellValue(jing);
            name_row.createCell(18).setCellValue(chajichajia);
            String status = dto.getKnumber() == null ? "未发货":"已发货";
            name_row.createCell(19).setCellValue(status);
            name_row.createCell(20).setCellValue(dto.getKnumber());
        }
        workbook.write(bos);
        byte[] barrays = bos.toByteArray();
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = "cXhwMiBRBiw_f2MPI6Pn-_IrpiQ5rQUQHQuu39be";
        String secretKey = "BiG0Yvlj3zWMqplekpV-ffqXncpF4x0C4hcxh0Be";
        String bucket = "cheng-images";
        String key = "excel/" + "orders/"+ OrderNoCreate.getExcelName()+".xls";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(barrays, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);

                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        Map map = new HashMap<>();
        map.put("downurl", key);
        return BaseResult.sucess(map);
    }

    @PostMapping("/createDeviceExcel")
    public BaseResult createDeviceExcel(@RequestBody CreateExcelDtoIn dtoIn) throws IOException {
        List<InventorysListDtoOut> list = new ArrayList<>();
        if (!dtoIn.getValue().isEmpty()) {
            String[] orders = dtoIn.getValue().split(",");
            for (int j = 0; j < orders.length; j++) {
                InventorysListDtoOut value = usermapper.getDeviceById(orders[j]);
                value.setYname(usermapper.getDeviceName(value.getYid()));
                value.setFname(usermapper.getDeviceFName(value.getFid()));
                value.setUname(usermapper.getUserName(value.getUid()));
                list.add(value);
            }
        }


        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("设备统计表");
        sheet.setDefaultColumnWidth(40);
        sheet.setDefaultRowHeightInPoints(20);
        List<String> hearList = new ArrayList<>();
        hearList.add("入库日期");
        hearList.add("设备型号");
        hearList.add("串码");
        hearList.add("登记人");
        hearList.add("出库日期");
        hearList.add("出库人");
        hearList.add("身份证");
        hearList.add("账号");
        hearList.add("备注");
        hearList.add("入库图片");
        hearList.add("出库图片");

        for (int i = 0; i < hearList.size(); i++) {
            if(i == 0 || i == 1 || i == 4|| i == 7|| i == 6){
                sheet.setColumnWidth(i,20*256);
            }if(i == 9 || i == 10){
                sheet.setColumnWidth(i,60*256);
            }else {
                sheet.setColumnWidth(i,15*256);
            }
        }
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < hearList.size(); i++) {
            row.createCell(i).setCellValue(hearList.get(i));
        }
        for (int j = 0; j < list.size(); j++) {
            InventorysListDtoOut dto = list.get(j);
            HSSFRow name_row = sheet.createRow(j + 1);
            name_row.createCell(0).setCellValue(dto.getCreate_time());
            name_row.createCell(1).setCellValue(dto.getYname()+"/"+dto.getFname());
            name_row.createCell(2).setCellValue(dto.getNumber());
            name_row.createCell(3).setCellValue(dto.getUname());
            name_row.createCell(4).setCellValue(dto.getUpdate_time());
            name_row.createCell(5).setCellValue(dto.getCname());
            name_row.createCell(6).setCellValue(dto.getIdCard());
            name_row.createCell(7).setCellValue(dto.getAccount());
            name_row.createCell(8).setCellValue(dto.getRemark());
            name_row.createCell(9).setCellValue(dto.getImage());
            name_row.createCell(10).setCellValue(dto.getCimage());

        }
        workbook.write(bos);
        byte[] barrays = bos.toByteArray();
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = "cXhwMiBRBiw_f2MPI6Pn-_IrpiQ5rQUQHQuu39be";
        String secretKey = "BiG0Yvlj3zWMqplekpV-ffqXncpF4x0C4hcxh0Be";
        String bucket = "cheng-images";
        String key = "excel/"+ "devices/" + OrderNoCreate.getExcelName()+".xls";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(barrays, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);

                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        Map map = new HashMap<>();
        map.put("downurl", key);
        return BaseResult.sucess(map);
    }

}

